import Vue from 'vue'
import {Toast} from 'vant'
import md5 from 'md5'
import {Base64} from 'js-base64'
import api from '../../api'
import {tr} from 'date-fns/locale'

const state = {
  // 登录凭证, 如token信息、有效期等
  logonCredentials: {},
  allUserInfo: {},
  // 用户当前的定位信息
  currentLocationInfo: {
    isDefault: true,
    cityOrTown: '北京',
    currentLongitude: 116.73,
    currentLatitude: 39.91,
    currentAddress: '北京市人民政府',
    currentFullAddress: '北京市通州区运河东大街57号'
  }
}

const actions = {
  // 登录时, 获取登录凭证并保存
  async getLoginCertificate({commit, state}, values) {
    const {account, password} = values
    const params = {
      account,
      password: Base64.encode(md5(password) + md5('jinpin888'))
    }
    const res = await api.user.reqLogin(params)
    if (res.code === 200) {
      const result = res.data
      // 保存token
      localStorage.setItem('allCertificate', JSON.stringify(result))
      Toast('登录成功')
      commit('save_certificate', {result})
    }
  },

  async getUserAllInfo({commit}) {
    const res = await api.user.reqUserAllInfo()
    if (res.code === 200) {
      const result = res.data

      localStorage.setItem('userInfo', JSON.stringify(result))
      commit('set_user_AllInfo', {result})
    }
  },

  // 退出登录
  logOut({commit}) {
    commit('LOGOUT')
  }
}

const mutations = {
  //保存定位信息
  set_currentLocationInfo(state, {result}) {
    state.currentLocationInfo = result
  },

  // 得到所有的用户信息
  set_user_AllInfo(state, {result}) {
    state.allUserInfo = result
  },

  // 保存登录凭证
  save_certificate(state, {result}) {
    state.logonCredentials = result
  },

  LOGOUT(state) {
    state.allUserInfo = {};
    state.logonCredentials = {};
    localStorage.removeItem('allCertificate')
    localStorage.removeItem('jobType');
    // 清空全部数据
    // localStorage.clear();
    sessionStorage.clear();
    // 这样可以优化定位体验
    Object.keys(localStorage).forEach(item => item.indexOf('STORAGE_') === -1 ? localStorage.removeItem(item) : '');

    // 使用字符串的includes方法
    // Object.keys(localStorage).forEach(item => !item.includes('STORAGE_') ? localStorage.removeItem(item) : '')
  }
}

export default {
  state,
  mutations,
  actions
}
